home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The Programmer Disk
/
The Programmer Disk (Microforum).iso
/
xpro
/
vb1
/
pro10
/
commdemo.frm
(
.txt
)
< prev
next >
Wrap
Visual Basic Form
|
1992-02-03
|
29KB
|
641 lines
Form_CommDemo
Communications Demo
Form1
Timer_CheckInBuf
Timer_ClearStatusWin
Label_ReceiveWin
Recieve Window
Text_ReceiveWin
Label_TransmitWin
Transmit Window
Text_TransmitWin
Label_StatusWinLab
Communications Status
Label_StatusWin
MNU_File
&File
MNU_File_Exit
E&xit
MNU_Connect
&Connect!
MNU_BaudMenu
&Baud
MNU_BaudRate
&1200
MNU_BaudRate
&4800
MNU_BaudRate
&9600
MNU_Events
E&vents
MNU_Events_CharDetect
&Character Detect
Form_Click
Form_LinkClose
Form_LinkErrorw
LinkErr
Form_LinkExecute
CmdStr`
Cancel
Form_LinkOpenl
@ Form_Load
Screen
Width4
Height4
OpenErrCode/
OpenCommPort
InBufSize
OutBufSize
ComDev;
MsgBoxCaption
DefMsgCaptionn
BaseComm
carriage
linefeed
OpenCommErr
Form_Unload
OpenCommError
DefaultLineSettings
DefaultEventSettings}
BaudRateT
ByteSizeC
Parity
NOPARITY
StopBits
ONESTOPBIT
RlsTimeOut`
CtsTimeOut
DsrTimeOuts
ModeControl
XonChar
XoffChar
XonLim
XoffLimP
peChar)
EofChar
EvtChar
Label_StatusBar
Caption
SetCommState
SetLineSettings
valuea
enablesV
containedr
received
fOutX
fDCBw
OpenComm7
SetEventSettings
DCBType
MNU_File_Exit_Click+
CloseCommZ
Timer_CheckInBuf_Timer
ReadCommJ
InBuf
NumCharsRead
Text_OutWin?
SelStart
SelTextZ
InBuff
SelLength
number
handshaking
anything~
buffer
displayg
windowF
Text_OutWin_Change[
Text_OutWin_GotFocus
Text_InWinL
Timer_CheckInBuf
Enabled
TrueI
ReadCommInterval)
Interval
ErrFlag
Text_InWin_Change=
Text_InWin_KeyPresss
KeyAsciiO
CharsWritten
WriteComm
OutBuff4
entered
Text_ReceiveWin_Change
Text_TransmitWin_Change
Text_TransmitWin
Text_ReceiveWin{
Text_TransmitWin_KeyDown
KeyCode
Shift
Text_TransmitWin_KeyPressE
EventAddr
SetCommEventMask
EV_ALL
Timer_ClearStatusBar_Timer!
Label2_Click
ShowStatus7
StatusText
Timer_ClearStatusBar
ClearStatusIntervall
False.
comst
status
DelayFlage
delay
DelayTime+
callingU
Windows
IE_OPEN
Response
ShowCriticalMessage/
ShowCritErrMessage
ShowCritErr
Label_ReceiveWin_Click
ErrTypev
ErrCode
@ ShowErrorJ
ExitRoutine
CloseComFlag:
ProcessCommError}
CommErr
GetCommErrorf
COMSTATr
CE_BREAK
CommStat
Message
ShowMessage
CE_CTSTO
CE_STSTO=
CE_DNS
CE_FRAME
CE_IOE
CE_MODE8
CE_OOPX
CE_OVERRUN
CE_PTO'
CE_RLSDTOu
CE_RXOVERL
CE_RXPARITY
CE_TXFULL
COMSTATType
CommConnectB
comments`
herej
CommID
ComID
GetCommStateJ
DCB_Type
MNU_Connect_Click
ConnectFlag
MNU_Connect
CommDisconnect
ConnectErrorr
ConnectErrFlag
IE_BADID
IE_BAUDRATE.
IE_BYTESIZE
IE_DEFAULT
IE_HARDWARE
IE_MEMORYV
IE_NOPEN
Text_ReceiveWin_GotFocus
CommConnectFlag
COMSTAT_Type5
ShowErrorMessage
ErrorFlag&
Label_TransmitWin_Click
ProcessCommEvents)
EventMaskD
GetCommEventMaskL
CurrentEventMaskU
EV_BREAK
ShowStateV
EV_CTR
EV_CTS`
EV_DSRj
EV_ERR
EV_PERR
EV_RING;
EV_RLSD
EV_RXCHAR
EV_RXFLAG
EV_FXFLAG
EV_TXEMPTY^
DisconnectComm?
Form_CommDemo
Form_Resize
Text_.
TxDelay
cbInQue
cbOutQuet
lpCommName
wInQueue
wOutQueuej
lpBuf
nSize
nEvtMask
CE_DSRTO
ODDPARITY
EVENPARITY
ONE5STOPBITS
TWOSTOPBITS
Label_StatusWin
alreadyp
opened
alread
ComDisconnect
MNU_File_Click
events
detectz
Label_StatusWin_ClickU
Label_StatusWinLab_Click
Disconnect
ProcessComError
Visual
Basic
Timer_ClearStatusWine
Timer_ClearStatusWin_Timer
GetOpenCommError
FlushCommH
BuildCommDCB6
MNU_BaudRate_Click
Index
BaudRate_Click
LastIndex
MNU_BaudRateT
Checked
PortID
MNU_Baud_Menu
MNU_BaudMenu
MNU_BaudMenu_Click
closed
ComStatusCode
GlobalDCB|
CharsWaiting'
MNU_Events_CharDetect_Click
CurrEventMask
MNU_Events_Click
MNU_Events_CharDetectg
CharDectEnabled
CharDetectEnabled
CharDetectEnabledFlag
MNU_Eventsx
Name of default communications device to be opened
COM input and output buffer sizess
Time interval to read the COM port (in milliseconds)
The maximum period of time (in milliseconds) for which a status bar message will be displayed
The time that message processing will be delayed (in seconds) while displaying a status bar message
Device Control Block (DCB) for the COM port. Contains all of the current line settings for the COM port.T
ID number representing the COM port. Set by calling the Windows API function SetCommState.
Flag indicating successful COM connection.
The current COM event settings. Set by calling the Windows API function SetCommEventMask
Form_Load
* This is the entry point of the program. Initialize global variables and center the form
* on the screen. The Windows API function BuildCommDCB is called to assign default values too
* the DCB (Device Control Block) data structure.
Initialize global variables representing carriager
return and carriage return linefeedn
Center the form on the screen
Disable the Events menu. The Events menu is enabled when the COM is connected
Initialize the COM DCB (Device Control Block) with default line settings
COM1:1200,N,8,1"
Form_Unload
Disconnect the COM only if the COM was connected
from this programh
SetLineSettings
* Set default line settings (e.g. baud rate, parity,
* data bits, stop bits and handshaking) by calling
* the Windows API function SetCommState.
* Note: The Chr$ function is used below to convert a numeric value
to a 1 byte character value. This is needed because a byte
is not supported as a numerical type under Visual Basic.
The Asc function can be used to get the value of a 1 byte
character representing a 1 byte numerical value.
Setting line settings ..."
Set the Id for the COM port. The COM port ID is returned by the Windows API function OpenComm
Set line settings for the COM port as 1200:N,8,1,CD0,CS0,DS0,RS,TB2048,RB2048t
The following parameter settings represent the default settings set by calling
BuildCommDCB in the Form_Load event procedure.
Set parameters as 1200: N,8,1M
DCB.BaudRate = 1200
'Other possible values include 300, 2400, 4800, 9600, 19200.
DCB.ByteSize = Chr$(8)
'Other possible values include 4,5,6,7
DCB.Parity = Chr$(NOPARITY)
'Other possible values include EVENPARITY, MARKPARITY, ODDPARITY, SPACEPARITY
DCB.StopBits = Chr$(ONESTOPBIT) 'Other possible values include ONE5STOPBITS, TWOSTOPBITS
Set timeout period for CD, CS and DS handshake lines respectively. Values
represent milliseconds. A value of zero represents an infinite wait effectively
disabling handshaking on that line. Possible values can range from 0 to 65,535s
for an unsiged integer or -32,768 to 32,767 for signed integers.
Carrier detect or receive-line-signal-detect (CD or RLSD) line (CD0)
Clear-to-send (CTS) line (CS0)
Data-set-ready (DSR) line (DS0))
The following bit flags are combined in the ModeControl field below. Becausec
the following are bit fields they cannot be represented as a field of a Type ... End Type
structurew
DCB.fBinary = 1
Specify binary mode. Setting this to zero causes an
EOF character (Chr$(26)) to signal the end of data.
DCB.fRtsDisabled = 1
Disable request-to-send line (RS). A zero value enables
the request-to-send linev
DCB.fParity = 0
Disable parity checking. A value of 1 enables parity checking
DCB.fOutCtsFlow = 0
Disable checking of clear-to-send line for output flow control
DCB.fOutxDsrFlow = 0
Disable checking of data-set-ready (DSR) line for output flow control
DCB.fDummy = 0 + 0
Two bit reserved fieldd
DCB.fDtrDisabled = 1
Disable the data-set-ready line (DTR). A value of 1 enables DTR.
DCB.fOutX = 0
Disable XON/XOFF during transmission.e
A value of 1 enables XON/XOFF.d
DCB.fInX = 0
Disable XON/XOFF during reception.i
A value of 1 enables XON/XOFF
DCB.fPeChar = 0
Disable the replace of parity error characters with the character
contained in the PeChar field. A value of 1 enables replacementt
of parity error characters with the character contained in then
PeChar field.
DCB.fNull = 0
Received null characters are not to be discarded. A value of 1c
specifies that null characters received will be discarded.d
DCB.fChEvt = 0
Reception of the character contained in the EvtChar field doesc
not signify an event. A value of 1 indicates that thet
reception of a character identical to the character contained
in the EvtChar field signifies and event.
DCB.fDtrFlow = 0
The DTR line is not used for receive flow control. A value of 1
indicates that the DTR line is used for receive flow control.
DCB.fRtsFlow = 0
The RTS line is not used for receive flow control. A value of 1
indicates that the DTR line is used for receive flow control.
DCB.fDummy = 0
Reserved
1100 0001
Binary representationr
of the above bit settings
Hex representation of the aboveu
bit settings
Based on the bit settings above
XON character to be used. Only used if the fOutX or fInX
fields are set to 1.
XOFF character to be used. Used only if the fOutX or fInX
fields are set to 1.
Specifies minimum number of characters allowed in the receive
buffer before the XON character is sent. Used only if the fOutX
or fInX fields are set to 1.
Specifies the maximum number of characters allowed in the
receive buffer before the XOFF character is sent. Used only
if the fOutX or fInX fields are set to 1.i
Character used to replace characters received with a parity
error. Used only if the fPeChar flag has been set to 1.
Specifies the character used to indicate end of data. Used
only if the the fBinary flag is set to 0.t
Character indicating an event. Used only if the fChEvt flag
is set to 1.
MNU_File_Exit_Click
* When the user selects Exit from the File menu, unload thee
* form, disconnect the COM - if it is already opened - and
* end the programm
Timer_CheckInBuf_Timer
* The code below represents a method of reading the COM port
* by calling the Windows API function ReadComm..
* Check the input buffer on each timer interval by calling
* the Windows API function ReadComm. If anything is found
* in the buffer, display it in the receive window.
COM status variable used by the Windows API function GetCommErrorb
Allocate a buffer (a text string of spaces) the size of the specified input buffer.f
Because the ReadComm API function expects to read to an existing buffer, failing
to initialize the buffer may result in unpredictable results or a Windows UAE.
Unlock the COM port if it had been locked as the result of a previous COM error.
The number of characters waiting in the receive buffer will be returned as part of the COMSTAT structure
Check to see if there are any characters waiting in the receive buffer
Call the Windows API function to read information from the input buffer. Read
all characters waiting in the input buffer.m
Check for COM error by calling the Windows API function GetCommError
If a COM error occurs, a message will be displayed and the COM port disconnected.f
Check for COM events by calling the Windows API function GetCommEventMask.
COM events, such as a ring detect, are displayed in the status window as they occur.
Check to see if any characters were read from the input buffer
Display the text read from the input buffer in
the receive window
SetEventSettings
* Specify which events are allowed to occur by calling the Windows API function
* SetCommEventMask..
Setting event settings ...
Place a check mark next to the Events menu item Character Detect indicating that char detect has been enabled
The following communication events are to be processed
Event (constant)
Descriptions
EV_BREAK
Set when a break is detected on input-
EV_ERR
Set when a line-status (CE_FRAME, CE_OVERRUN, CE_RXPARITY) error occurso
EV_RING
Set when a ring indicator is detected
EV_RXCHAR
Set when a character is received and placed in the COM receive buffer
EV_TXEMPTY
Set when the last character in the COM transmit buffer is sent
Other possible values include:
EV_CTS
Set when the clear-to-send (CTS) signal changes stateu
EV_DSR
Set when the data-set-ready (DTR) signal changes state
EV_PERR
Set when a printer error is detected on a parallel device
EV_RLSD
Set when the receive-line-signal-detect (RLSD) signal changes state
EV_RXFLAG
Set when the event character is received and placed in the receive buffer
Combine the events to be processed into the event mask. The bitwise Or operator is used toi
combine the bit patterns of the constants representing the COM events.
All possible communciations events may occur
Text_TransmitWin_KeyPress
* Writes the character for each key press to the output*
* buffer by calling the Windows API function WriteComm
Convert the ASCII code of the key pressed to an ASCII characterr
Write the character to the COM output buffer by callingl
the Windows API function WriteComm.u
Check for COM error by calling the Windows API function GetCommError
If a COM error occurs, a message will be displayed and the COM port
disconnected.r
Check for COM events. COM events, such as a ring detect, are,
displayed in the status window as they occur.r
ShowStatus
* Display a caption within the status window at the bottom
* of the main display window
Show a message in the status window
Delay (allow for the message to be read by the user) for
a specified period of time
Get the current clock count
Loop for the amount of time specified by DelayTime (in seconds) without processing other Windows events
Enable a timer to cause the status window to be clear after a specified period of time
ShowError
* Display standard error messages based on the type of error that occurred..
* The messages are displayed in a modal message box (MsgBox).
Show message box indicating that an error occurred
attempting to open the COM port
Error occurred attempting to open
Connection not established
Error attempting to set line settings"
Connection not established
ProcessCommError
* Determines if an error occurred after a COM operation. *
* If an error occurred, a message is displayed indicating that the COM will be
* disconnected. It is the responsibility of the calling routine to disconnect
* the COM.
* When an error occurs, Windows locks the COM port. Calling the
* Windows API function GetCommError causes the COM port to be unlocked.
COM status variable used by the Windows API function GetCommErrorE
Find out if an error occured. Calling GetCommError clears
the error and causes Windows to unlock the COM port.
One or more of the following errors may have occurred
Break condition detected
Clear-to-send (CTS) timeout"
Data-set-ready (DSR) timeout
Parallel device is not selected"
Framing error detected
Device I/O error occurred"
attempting to communicate with parallel device
Requested mode is not supported"
Out of paper on parallel device"
Overrun error detected
Timeout attempting to communicate with
parallel device"
Receive-line-signal-detect (RLS) timeout
Receive buffer overflow"
Parity error detected"
Transmit buffer full
CommConnect
* Connect to the communications port by calling the following Windows API functions:
OpenComm
GetCommState
SetCommState
SetCommEventMask
* The return values of OpenComm and SetCommState are tested for an error. If an
* error occurs a message is displayed and the COM remains disconnected.r
Assume that no error will occur opening COMr
Opening COM port ...
Attempt to open the COM port specifying the input and output buffer sizes
Check to see if the COM port was successfully opened
If the COM was successfully opened the return value of OpenComm represents the COM ID.
Set communications line settings such as baud rate,d
parity, data bits, stop bits and hardware handshaking.
Select the allowable communication events
by calling the Windows API function SetCommEventMask
Display a message box indicating a critical error and
end the programg
Enable the timer to begin reading the COM input buffer.t
Get the COM ID used in the call to BuildCommDCBa
COM device already opened"
Do you wish to use it anyway
Close the com port if the user selected Yes from the message box
The user chose not to use the COM port that is already opened.
Show a critical error and terminate the programa
A critical error occurred when attempting to open the COM port.p
Attempt to open the COM port again if the COM port is already open, but the user wants to use it anyway
Return False if an error occurred attempting to connectn
Return True if connection was successful
MNU_Connect_Click
* When the user selects Connect! from the menu, connect to the COM port if itt
* is not already opened by calling CommConnect.
* When the user selects Disconnect! from the menu, disconnect from the COM
* port if it is already opened by calling ComDisconnect.
See if the COM is already a connected
Disconnect the COM port by calling the Windows API function CloseComms
Connect to the COM port by calling the following Windows API functions:u
OpenComm
SetCommStateM
SetCommEventMaskS
Make sure there was no error in connecting to the COM port.C
If an error occurred, no attempt will be made to connect the COM port.
&Disconnect!
Enable the transmit and receive windowss
CommDisconnect
* Disconnect from the COM port by calling the Windows API function CloseComm
* Disable the transmit and receive windows and reset the menu caption.
Closing COM port ...
Flush the transmit buffer
Flush the receive buffer
Call the Windows API function to close the COM port.
The return value represents whether the comm was successfully closed or not, it is
not used.n
Invalid the COM ID to indicate that the COM was closed
Turn off timer used to check COM receive bufferu
Disable the transmit and receive windows
Change the menu caption and connection status flag
&Connect!"
Disable the events menua
Text_ReceiveWin_GotFocus
* Do not allow the focus to be set to the receive window.*
* If the user attempts to select the receive window,
* restore focus to the transmit window.c
ProcessCommEvents
* Check to see if a communications event occurred by calling the Windows
* API function GetCommEventMask. The event, such as a ring, is reported
* in the status window.v
Call Windows API function to get the COM event mask. The event mask iss
a pattern of bits which represents one or more of the events below.n
Check for the following events. The events that are reported
are dependent on the event mask that was passed to SetCommEventMaskt
Break detected on input"
Clear-to-send (CTS) line changed state
Data-set-ready (DTR) line changed state"
Line status (framing, overrun or parity) error occurred"
Printer error occurred
Ring detected"
Receive-line-signal-detect (RLSD) or carrier-detect (CD) line changed status
Character received
Event character received
Last character sent: transmit buffer empty
Timer_ClearStatusWin_Timer
* After a status message has been displayed
* for a certain interval, clear the status window-
GetOpenCommError
* FUNCTION: GetOpenCommError
* PURPOSE: Returns an error message based on the specified
error code. The error code is interrupted as
related to an error when opening the COM device.
This function handles all possible return codes.
from the Windows API function OpenComm.r
* PARMS:
OpenErrCode - Specifies the error code relatede
to the opening the COM porti
* RETURNS: A string containing the error message associated
with the error coden
Invalid or unsupported ID"
Unsupported baud rate"
Invalid byte size"
Error in default parameters"
Hardware not present
Unable to allocate queues"
Device not open"
Device already opened"
MNU_BaudRate_Click
* Change the COM line settings to reflect the new baud rate selected by the user..
* Note that the baud rate (as with any line setting) can be changed if the portt
* is open or closed. If the baud rate of the device being communicated with doess
* not change, this could lead to unexpected behavior..
Get the baud rate selected
Set the baud rate
Modify the COM line settings with the new baud rate
Put a check mark next to the baud rate selectedr
Take the check mark away from the last baud rate selectedl
MNU_Events_CharDetect_Click
* Set or disable the ability to detect characters received
* from the COM.
* When enabled, character related events are displyed in
* the status window when a character is received
Get the status of the menu selection
Toggle the check mark next to the menu itemv
Disable character detect events by setting the EV_RXCHAR bit to 0e
Enable character detect events by setting the EV_RXCHAR bit to 1
Set the COM event settings by calling a Windows API function